//
//  FRQResellerGalleryViewController.m
//  FRQBluetoothKit_Example
//
//  Created by admin on 2023/10/22.
//  Copyright © 2023 xuchunhai. All rights reserved.
//

#import "FRQResellerGalleryViewController.h"
#define KCellID @"MonthCardPayViewsID"
#define KHedderID @"MonthCardPayViewsHedderID"
#define KFooterID @"MonthCardPayViewsFooterID"
#import "ResellerGalleryViews.h"
#import "ResellerGalleryCells.h"
#import "YSHYClipViewController.h"
#import "FRQCroppedImageViewController.h"
#import "SVGKImage.h"
#import "SVGKit.h"
@interface FRQResellerGalleryViewController ()<ClipViewControllerDelegate>
@property (nonatomic,strong) ResellerGalleryViews *resellerGalleryView;
@property (nonatomic,strong) NSArray *arrImageList;
@property (nonatomic,assign) NSInteger selectIndex;
@property (nonatomic,assign) NSInteger pageNum;
@property (nonatomic,assign) NSInteger totalPage;
@end

@implementation FRQResellerGalleryViewController
///user/nft/list
///

-(void)userNftList:(HJHttpRequest)callback{
    
    NSDictionary *dic=@{@"pageNum":[NSString stringWithFormat:@"%ld",self.pageNum],
                        @"pageSize":@12
    };
    NSString *urlName;
    
    if(KuserType==0){
        urlName=@"app/user/nft/list";
        if(self.userShowDealerNft==1){
            urlName=@"app/sys/user/nft/list";
        }
    }else{
        urlName=@"app/sys/user/nft/list";
    }
    
    [skNetTools skGETWithURL:[NSString stringWithFormat:@"%@%@",skURL,urlName] parameters:dic cachePolicy:0 callback:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        NSLog(@"数据=%@",responseObject);
        skNetModel *model=[skNetModel mj_objectWithKeyValues:responseObject];
        if(model.code==200){
            self.arrImageList=[model.data objectForKey:@"data"];
            self.totalPage=[[model.data objectForKey:@"totalPage"] intValue];
            [self.collectionView reloadData];
        }
        callback(responseObject,error);
    }];
}
-(ResellerGalleryViews *)resellerGalleryView{
    if (nil==_resellerGalleryView) {
        _resellerGalleryView=skXibView(@"ResellerGalleryViews");
        @weakify(self)
        [[_resellerGalleryView.btnSelect rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            if(self.arrImageList.count==0){
                [SkToast SkToastShow:@"No picture"];
                return;
            }
            NSDictionary *dic=self.arrImageList[self.selectIndex];
            NSString *imageName=[dic objectForKey:@"imageUrl"];
            
            UIImageView *imageV=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
            
            [imageV sd_setImageWithURL:[NSURL URLWithString:imageName] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                YSHYClipViewController * clipView = [[YSHYClipViewController alloc]initWithImage:image];
                clipView.delegate = self;
                clipView.clipType = 0;
                clipView.radius = 170;   //设置 裁剪框的半径
                [self.navigationController pushViewController:clipView animated:YES];
            }];        }];
    }
    return _resellerGalleryView;
}
#pragma mark - ClipViewControllerDelegate
-(void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage
{
    
}
-(UICollectionView *)collectionView{
    if (nil==_collectionView) {
        
        //1.初始化layout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置collectionView滚动方向
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        //设置headerView的尺寸大小
        layout.headerReferenceSize = CGSizeMake(skScreenWidth, 400);
        //设置尾部的尺寸大小
//        layout.footerReferenceSize = CGSizeMake(self.frame.size.width, 30);
        //        该方法也可以设置itemSize
        
        
        layout.itemSize =CGSizeMake((skScreenWidth-120)/3, 89);
        _collectionView=[[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        
        [self.view addSubview:_collectionView];
        [_collectionView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
        
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_topLayoutGuide).offset(42);
            make.left.mas_equalTo(39);
            make.right.mas_equalTo(-39);
            make.height.mas_equalTo(450);
        }];
        //3.注册collectionViewCell
        //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:KCellID];
        //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KHedderID];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:KFooterID];
//        _collectionView.bounces = NO;
        //4.设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator=NO;
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if(self.walletBack==1){
        @weakify(self)
        [[[self skCreatBtn:@"back_ico" btnTitleOrImage:(btntypeImage) btnLeftOrRight:(btnStateLeft)] rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }
    self.pageNum=1;
    if(self.userShowDealerNft==1){
        self.title=skUser.resellerName;
    }else{
        if(self.walletBack==1){
            self.title=@"My Wallets";
        }else{
            self.title=@"Display Gallery";
        }
        
    }
    [self.view addSubview:self.resellerGalleryView];
    if(KuserType==1){
        self.resellerGalleryView.btnSelect.hidden=YES;
    }
    // Do any additional setup after loading the view.
    [self.collectionView reloadData];
    
    self.collectionView.backgroundColor=skUIColorFromRGB(0x1c1f2a);
    [self userNftList:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
    }];
    
    [self SetupRightZLingItem:@"refresh_ico_gallery" isZLingImage:YES];
    
    self.collectionView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNum=1;
        [self userNftList:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
            [self.collectionView.mj_header endRefreshing];
        }];
    }];
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter  footerWithRefreshingBlock:^{
        if(self.totalPage>self.pageNum){
            self.pageNum++;
        }
        [self userNftList:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
            [self.collectionView.mj_footer endRefreshing];
        }];
        
    }];
}
- (void)BtnRightZLingAction:(UIButton *)sender{
    self.pageNum=1;
    [self userNftList:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark mark - 代理方法UICollectionReusableView
#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arrImageList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:KCellID forIndexPath:indexPath];
    
    for (UIView *view in cell.contentView.subviews) {
        if (view) {
            [view removeFromSuperview];
        }
    }
    ResellerGalleryCells *view=skXibView(@"ResellerGalleryCells");
    view.btnSelect.hidden=YES;
    NSDictionary *dic=self.arrImageList[indexPath.row];
    NSString *imageName=[dic objectForKey:@"imageUrl"];
    [view.imageIcon sd_setImageWithURL:[NSURL URLWithString:imageName] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if([imageName containsString:@".svg"]){
            view.imageIcon.image=[self svgImageNamed:imageName size:CGSizeMake(200, 200)];
        }
    }];
    
    
    
    
    if(indexPath.row==self.selectIndex){
        view.btnSelect.hidden=NO;
    }
    if (KuserType==1) {
        view.btnSelect.hidden=YES;
    }
    [cell.contentView addSubview:view];
    
    return cell;
}

- (UIImage *)svgImageNamed:(NSString *)name size:(CGSize)size {
    SVGKImage *svgImage = [SVGKImage imageWithContentsOfURL:[NSURL URLWithString:name]];
    svgImage.size = size;
    UIImage *image=svgImage.UIImage;
    return image;
}
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((skScreenWidth-120)/3, 89);
}

//footer的size
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    return CGSizeMake(10, 10);
//}

//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(skScreenWidth-90, 0);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(1, 7, 1, 7);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}


//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind ==UICollectionElementKindSectionHeader){
        
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KHedderID forIndexPath:indexPath];
        
        for (UIView *view in headerView.subviews) {
            if (view) {
                [view removeFromSuperview];
            }
        }
        
        return headerView;
    }
    
    if (kind ==UICollectionElementKindSectionFooter) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:KFooterID forIndexPath:indexPath];
        
        
        
        return headerView;
    }
    return nil;
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectIndex=indexPath.row;
    [self.collectionView reloadData];
}

@end
